package lesson.clazz;

import lesson.base.BaseServlet;
import lesson.grade.Grade;
import lesson.grade.GradeService;
import lesson.permission.Role;
import lesson.user.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.List;

@WebServlet("/clazz/*")
@Role(User.ROLE_ADMIN)
public class  ClazzServlet extends BaseServlet {

    private ClazzService clazzService = new ClazzService();
    private GradeService gradeService = new GradeService();
    /**
     * 班级管理的首页
     */
    public void index() {
        forwardJsp("/pages/clazz/index");
    }

    /**
     * 班级管理的编辑页面
     */
    public void edit(Integer id) {

        List<Grade> grades = gradeService.list(null);

        if (id != null) {
            Clazz clazz = clazzService.getById(id);
            getRequest().setAttribute("clazz", clazz);
        }
        getRequest().setAttribute("grades", grades);
        forwardJsp("/pages/clazz/edit");
    }


    /**
     * 查询班级
     */
    public void list(Integer gradeId, String keywords) throws ServletException, IOException {
        List<Clazz> list = clazzService.list(gradeId, keywords);
        writeJSON(true, null, list);
    }


    /**
     * 删除班级
     * @param id
     */
    public void del(Integer id) throws ServletException, IOException {
        String result = clazzService.del(id);
        if (result == null) {
            writeJSON(true);
        } else {
            writeJSON(false, result);
        }
    }


    /**
     * 保存班级
     * @throws ServletException
     * @throws IOException
     */
    public void save(Clazz clazz) throws ServletException, IOException {

        String result = clazzService.saveClazz(clazz);
        if (result == null) {
            writeJSON(true);
        } else {
            writeJSON(false, result);
        }
    }


}
